#include<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<cstdio>
#include<algorithm>
#include<string>
#include<string.h>
#include<queue>
#include<math.h>
#include<set>
#include<functional>
using namespace std;
using ull = unsigned long long;
#define int long long
//using i128 = __int128_t;
inline int inc(int x, int v, int mod) { x += v;return x >= mod ? x - mod : x; }//代替取模+
#define endl '\n'
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;

const int N = 2e3 + 10, M = 1e5 + 10;

inline int read()
{
    int x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9')
    {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9')
        x = x * 10 + ch - '0', ch = getchar();
    return x * f;
}

int x1[] = {0,0,0,1,-1};
int yy[] = {0,1,-1,0,0};

void solve()
{
    int n,m;
    cin >> n >> m;
    vector<vector<char>> arr(n + 10,vector<char>(m + 10));

    for(int i = 1; i <= n; i ++)
    {
        for(int j = 1; j <= m; j ++)
        {
            cin >> arr[i][j];
        }
    }
    vector<vector<bool>> judge(n + 10,vector<bool>(m + 10));
    set<pair<int,int>>pp;
    int ans = 0x3f3f3f3f;
    int cnt = 0;
    auto dfs =[&](auto &&self,int x,int y) -> void
    {
        if(ans <= cnt) return;
        for(int i = 1; i <= 4; i ++)
        {
            int newx = x + x1[i];
            int newy = y + yy[i];
            if(newx > n || newy > m || newx < 1 || newy < 1 || judge[newx][newy] == 1 || pp.find({newx,newy}) != pp.end()) continue;
            if(arr[newx][newy] == '1')
            {
                judge[newx][newy] = 1;
                self(self,newx,newy);
                if(ans <= cnt) return;
            }
            else
            {
                pp.insert({newx,newy});
                cnt ++;
                if(ans <= cnt) return;
            }
        }
        if(ans <= cnt) return;
    };

    for(int i = 1; i <= n; i ++)
    {
        for(int j = 1; j <= m; j ++)
        {
            if(judge[i][j] == 0 && arr[i][j] == '1')
            {
                cnt = 0;
                judge[i][j] = 1;
                dfs(dfs,i,j);
                ans = min(cnt,ans);
                pp.clear();
            }
        }
    }

    cout << ans << endl;
}
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    int tt;
    //cin >> tt;
    tt = 1;
    while (tt--)
    {
        solve();
    }
}